<template>
  <div class="container" style="height: 100%">
    <div class="flex_cm" style="height: 100%">
      <search
        :data="header_list"
        @changeIsShow="
          (e) => {
            header_list[e].isShow = !header_list[e].isShow
            header_list[e].value =
              header_list[e].type == 'input_number' ? ['', ''] : ''
          }
        "
        @search="search_key"
        @reset="
          header_list.forEach((item) => {
            item.value = item.type == 'input_number' ? ['', ''] : ''
          }),
            search_key()
        "
      ></search>
      <div class="p_0_10 bg_fff flex1">
        <div class="flex_js p_10_0">
          <div class="c_666 fw">战略合作企业合同管理</div>
          <div class="flex">
            <el-button
              type="primary"
              @click=";(show_box = true), (is_exam = false)"
              v-if="has_role_list[3].has_role"
              >新增合同</el-button
            >

            <setTable
              :data="header_list"
              :height_size="height_size"
              @changeShowTable="
                (e) => {
                  header_list[e].showTable = !header_list[e].showTable
                }
              "
              @resetTableSet="
                () => {
                  header_list.forEach((item) => {
                    item.showTable = true
                  })
                }
              "
              @changeHeightSize="
                (e) => {
                  height_size = e
                }
              "
            ></setTable>
          </div>
        </div>
        <el-table
          style="text-align: center"
          :data="list"
          :max-height="max_height"
          border
          highlight-current-row
          v-loading="loading"
          :default-sort="{ prop: 'createTime', order: '' }"
          :row-style="{
            height: height_size == 2 ? '50px' : '',
          }"
          :cell-style="{
            padding: height_size == 3 ? '0' : '',
          }"
        >
          <el-table-column
            type="index"
            label="序号"
            width="80px"
          ></el-table-column>
          <el-table-column
            v-if="header_list[0].showTable"
            label="合同编号"
            prop="code"
            sortable
          ></el-table-column>
          <el-table-column
            v-if="header_list[1].showTable"
            label="合同名称"
            prop="name"
            sortable
          ></el-table-column>
          <el-table-column
            v-if="header_list[2].showTable"
            label="产品类型"
            sortable
            prop="productId"
          >
            <template #default="scope">{{
              scope.row?.productId?.dictValue
            }}</template>
          </el-table-column>
          <el-table-column label="开始时间" v-if="header_list[3].showTable">
            <template #default="scope: any" sortable prop="startTime">
              <div>
                {{ formatDate(parseInt(scope.row?.startTime), 'yyyy-MM-dd') }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="结束时间"
            sortable
            prop="endTime"
            v-if="header_list[4].showTable"
          >
            <template #default="scope: any">
              <div>
                {{ formatDate(parseInt(scope.row?.endTime), 'yyyy-MM-dd') }}
              </div>
            </template></el-table-column
          >
          <el-table-column
            v-if="header_list[5].showTable"
            sortable
            label="战略合作客户"
            prop="enterpriseName"
          ></el-table-column>
          <el-table-column
            v-if="header_list[6].showTable"
            label="合同金额"
            sortable
            prop="amount"
          ></el-table-column>
          <el-table-column
            v-if="header_list[7].showTable"
            label="审核状态"
            sortable
            prop="verifyStatus"
          >
            <template #default="scope: any">
              {{ scope.row?.verifyStatus == 1 ? '待审核' : '已审核' }}
            </template>
          </el-table-column>
          <el-table-column
            label="合同状态"
            sortable
            v-if="header_list[8].showTable"
            prop="verifyStatus"
          >
            <template #default="scope: any">
              <div v-if="scope.row?.isExpire">已过期</div>
              <div v-if="!scope.row.isExpire && scope.row.verifyStatus == 2">
                <div v-if="scope.row.status == 1">
                  <span
                    v-if="scope.row?.startTime > Date.parse(new Date() as any)"
                    sttyle="color:#EE5656"
                    >未生效</span
                  >
                  <span
                    class="flex_cc"
                    v-if="scope.row?.startTime < Date.parse(new Date() as any) && scope.row?.endTime > Date.parse(new Date() as any)"
                  >
                    剩余
                    <span
                      :style="{color:days(scope.row?.endTime, Date.parse(new Date() as any)) < 10 ? '#EE5656' : '' }"
                      >{{
                        days(scope.row?.endTime, Date.parse(new Date() as any))
                      }}</span
                    >
                    天
                    <div
                      class="flex_cc m_left5"
                      v-if="
                        scope.row?.pauseTimeList?.length &&
                        scope.row?.pauseTimeList[0]?.status == 0
                      "
                    >
                      <el-tooltip
                        :content="
                          '将于 ' +
                          formatDate(
                            parseInt(scope.row.pauseTimeList[0]?.startTime),
                            'YYYY-MM-DD'
                          ) +
                          ' 至 ' +
                          scope.row.pauseTimeList[0]?.endTime +
                          ' 暂停'
                        "
                        placement="bottom"
                      >
                        <img
                          src="@/assets/img/tishi.png"
                          style="height: 16px; width: 16px; margin: auto"
                          alt=""
                        />
                      </el-tooltip>
                    </div>
                  </span>
                </div>
                <div v-show="scope.row?.status == 0">已停用</div>
                <div v-if="scope.row.status == 2" class="flex_cc">
                  <span>已暂停</span>
                  <el-tooltip
                    :content="
                      '暂停时间：' +
                      formatDate(
                        parseInt(scope.row?.pauseTimeList[0]?.startTime),
                        'YYYY-MM-DD'
                      ) +
                      ' 至 ' +
                      scope.row?.pauseTimeList[0]?.endTime
                    "
                    placement="bottom"
                  >
                    <img
                      src="@/assets/img/tishi.png"
                      style="height: 16px; width: 16px; margin-left: 5px"
                      alt=""
                    />
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="header_list[9].showTable"
            label="备注"
            prop="remark"
            sortable
          ></el-table-column>
          <el-table-column label="操作" width="160px">
            <template #default="scope: any">
              <div class="flex_cc gap_20" v-show="scope.row?.verifyStatus != 1">
                <el-tooltip
                  content="详情"
                  placement="bottom"
                  v-show="has_role_list[4].has_role"
                >
                  <svgBtn
                    icon="table_info"
                    style="font-size: 20px"
                    @click="pass_list(scope.row)"
                  ></svgBtn>
                </el-tooltip>
                <el-tooltip
                  :content="
                    scope.row?.pauseTimeList?.length &&
                    scope.row?.pauseTimeList[0]?.status == 0
                      ? '编辑暂停'
                      : '暂停'
                  "
                  placement="bottom"
                  v-show="scope.row?.status == 1 && scope.row?.endTime > Date.parse(new Date() as any) && scope.row?.startTime <= Date.parse(new Date() as any)"
                >
                  <svgBtn
                    icon="table_status_disable"
                    style="font-size: 20px"
                    :color="
                      scope.row?.pauseTimeList?.length &&
                      scope.row?.pauseTimeList[0]?.status == 0
                        ? '#999'
                        : '#45474A'
                    "
                    @click="suspend_list(scope.row)"
                  ></svgBtn>
                </el-tooltip>
                <el-tooltip
                  content="重启"
                  placement="bottom"
                  v-show="!scope.row?.isExpire && scope.row?.status == 2"
                >
                  <svgBtn
                    icon="table_status_enable"
                    style="font-size: 20px"
                    @click="restart_list(scope.row)"
                  ></svgBtn>
                </el-tooltip>
              </div>
              <span v-show="scope.row?.verifyStatus == 1">
                <table_edit
                  :status="true"
                  :role="has_role_list"
                  @edit_item_status="pass_list(scope.row)"
                  @edit_item="edit_list(scope.row)"
                  @delete_item="delete_list({ item: scope.row, type: 0 })"
                ></table_edit>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <dialog_box
      @submit_delete="submit_delete"
      @close="show_delete_box = false"
      :delete_name="delete_name"
      :show_delete_box="show_delete_box"
      :delete_box_status="delete_box_status"
    ></dialog_box>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      @close="resetForm(addcoopenterpriseform)"
      size="40%"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <template #title>
        <h4 v-if="is_exam">审核</h4>
        <div v-else>
          <h4 v-if="add_form_data.id == ''">新增战略合作企业合同</h4>
          <h4 v-else>编辑战略合作企业合同</h4>
        </div>
      </template>
      <template #default>
        <el-form
          :model="add_form_data"
          ref="addcoopenterpriseform"
          :rules="rules"
          label-width="150px"
        >
          <el-form-item label="合同编号" prop="code">
            <el-input
              v-model="add_form_data.code"
              placeholder="请输入"
              show-word-limit
              :disabled="is_exam"
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="合同名称" prop="name">
            <el-input
              v-model="add_form_data.name"
              placeholder="请输入"
              show-word-limit
              maxlength="50"
              :disabled="is_exam"
            ></el-input>
          </el-form-item>
          <el-form-item label="产品类型" prop="productId">
            <el-select v-model="add_form_data.productId" :disabled="is_exam">
              <el-option
                v-for="item in product_list"
                :key="item.id"
                :value="item.dictCode"
                :label="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="战略合作企业" prop="enterpriseId">
            <!-- <el-input placeholder="请输入"></el-input> -->
            <el-select
              v-model="add_form_data.enterpriseId"
              filterable
              :disabled="is_exam"
              @change="select_enterprise"
            >
              <div v-for="item in enterprise_list" :key="item.id">
                <el-option
                  :label="item.name + (item.levelId == '4' ? ' (战略)' : '')"
                  :value="item.id"
                ></el-option>
              </div>
            </el-select>
          </el-form-item>
          <el-form-item label="合同开始" prop="startTime">
            <el-date-picker
              :disabled="is_exam"
              v-model="add_form_data.startTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="x"
              placeholder="请选择"
              :disabled-date="disabledStartTime"
              @change="
                () => {
                  add_form_data.endTime =
                    add_form_data.endTime < add_form_data.startTime
                      ? ''
                      : add_form_data.endTime
                }
              "
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="合同结束" prop="endTime">
            <el-date-picker
              :disabled="is_exam || add_form_data.startTime == ''"
              v-model="add_form_data.endTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="x"
              placeholder="请选择"
              :disabled-date="disabledEndTime"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="合同金额" prop="amount">
            <el-input
              :disabled="is_exam"
              v-model="add_form_data.amount"
              placeholder="请输入"
              @input="
                add_form_data.amount = add_form_data.amount.replace(
                  /^(0+)|[^\d]+/g,
                  ''
                )
              "
            ></el-input>
          </el-form-item>
          <el-form-item label="合同状态">
            <el-radio
              :disabled="is_exam"
              v-model="add_form_data.status"
              :label="1"
              >启用</el-radio
            >
            <el-radio
              :disabled="is_exam"
              v-model="add_form_data.status"
              :label="0"
              >禁用</el-radio
            >
            <el-radio disabled v-model="add_form_data.status" :label="2"
              >暂停</el-radio
            >
          </el-form-item>
          <el-form-item label="合同备注">
            <el-input
              show-word-limit
              type="textarea"
              :disabled="is_exam"
              v-model="add_form_data.remark"
              placeholder="请输入"
              maxlength="300"
            ></el-input>
          </el-form-item>
          <el-form-item label="合同附件" prop="url">
            <upload
              v-if="!is_exam"
              :imageUrl="add_form_data.url"
              :fileNames="add_form_data.fileNames"
              :width="100"
              :height="100"
              :uploadUrl="serviceApi.contract_upload"
              :downloadUrl="serviceApi.contract_download"
            ></upload>
            <div v-else>
              <div class="flex_wp m_top10">
                <div
                  v-for="(item, index) in add_form_data.url"
                  class="p_rel flex_cc m_bottom10 m_right10"
                  style="object-fit: scale-down"
                >
                  <el-tooltip
                    :content="add_form_data.fileNames[index]"
                    placement="bottom"
                  >
                    <div
                      @click="download(item)"
                      @mouseenter="down_index = index"
                      @mouseleave="down_index = Number"
                      style="width: 100px; height: 100px"
                    >
                      <div
                        v-show="down_index == index"
                        class="down_icon flex_cc"
                      >
                        <el-icon :size="30" color="#777"><Download /></el-icon>
                      </div>
                      <img
                        src="@/assets/img/file_default.png"
                        style="width: 100px; height: 100px"
                      />
                    </div>
                  </el-tooltip>
                </div>
              </div>
            </div>
          </el-form-item>
          <div class="m_top10 tr">
            <el-button @click="resetForm(addcoopenterpriseform)"
              >取消</el-button
            >
            <span v-if="verifyStatus == 1" class="m_left10">
              <el-button
                v-if="!is_exam"
                type="primary"
                :loading="btn_loading"
                @click="submit(addcoopenterpriseform)"
                >确定</el-button
              >
              <el-button v-else type="primary" @click="exam">审核</el-button>
            </span>
            <span v-else class="m_left10">
              <el-button
                v-if="!is_exam"
                type="primary"
                :loading="btn_loading"
                @click="submit(addcoopenterpriseform)"
                >确定</el-button
              >
            </span>
          </div>
        </el-form>
      </template>
    </el-drawer>
    <el-drawer
      v-model="suspend_box"
      direction="rtl"
      size="40%"
      destroy-on-close
      :close-on-click-modal="false"
      @close="suspend_box_cancel"
    >
      <template #title>
        <h4>暂停期限</h4>
      </template>
      <template #default>
        <el-form label-width="120px">
          <el-form-item label="暂停日期">
            <el-date-picker
              v-model="suspend_form.startTime"
              type="date"
              placeholder="请选择"
              format="YYYY-MM-DD"
              value-format="x"
              :disabled-date="startTimeDisabled"
            ></el-date-picker>
          </el-form-item>
          <div class="fs_14 c_999" style="margin-left: 120px">
            暂停日期不选择即立即暂停
          </div>
          <el-form-item label="重启日期">
            <el-date-picker
              v-model="suspend_form.endTime"
              type="date"
              placeholder="请选择"
              format="YYYY-MM-DD"
              value-format="x"
              :disabled-date="endTimeDisabled"
            ></el-date-picker>
          </el-form-item>
          <div class="fs_14 c_999" style="margin-left: 120px">
            暂停区间不包含重启日当天
          </div>
          <el-form-item label="">
            <el-checkbox v-model="suspend_form.isPutOff"
              >重启后合同到期日顺延</el-checkbox
            >
          </el-form-item>
          <el-divider></el-divider>
          <div class="m_top10 tr">
            <el-button
              type="warning"
              @click="suspend_cancel"
              v-if="suspend_form.id != ''"
              >关闭暂停</el-button
            >
            <el-button @click="suspend_box_cancel">取消</el-button>
            <el-button type="primary" @click="suspend_submit()">确定</el-button>
          </div>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { check_role, formatDate, days, handle_search_key } from '@/utils/utils' // 权限校验
import { Download } from '@element-plus/icons-vue'
import search from '@/view/components/search.vue'
import dialog_box from '@/view/components/dialog_box.vue'
import table_edit from '@/view/components/table_edit.vue'
import svgBtn from '@/components/svg_button.vue'
import upload from '@/view/components/upload.vue'
import setTable from '@/view/components/setTable.vue'
import { onMounted, ref, reactive, onUnmounted, computed } from 'vue'
import { FormInstance, ElMessage, ElMessageBox, FormRules } from 'element-plus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { useStore } from 'vuex'
const store = useStore()
// 页面权限组
const has_role_list = ref([
  { path: 'cooperation/pass', has_role: false },
  { path: 'cooperation/put', has_role: false },
  { path: 'cooperation/delete', has_role: false },
  { path: 'cooperation/post', has_role: false },
  { path: 'cooperation/info', has_role: false },
])
const max_height = ref()
const disabledEndTime = (time) => {
  return time.getTime() < add_form_data.value.startTime + 3600 * 1000 * 24
}
const disabledStartTime = (time) => {
  return contract_list.value.length
    ? time.getTime() < contract_list.value.at(-1).endTime
    : ''
}
// type FormInstance = InstanceType<typeof ElForm>
const addcoopenterpriseform = ref<FormInstance>()
const customize = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入合同编号'))
  }
  setTimeout(() => {
    var reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g')
    if (reg.test(value)) {
      callback(new Error('合同编号不能包含汉字'))
    } else {
      callback()
    }
  }, 1000)
}
const rules = reactive<FormRules>({
  code: [{ required: true, validator: customize, trigger: 'blur' }],
  name: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
  enterpriseId: [
    { required: true, message: '请选择战略合作企业', trigger: 'change' },
  ],
  amount: [{ required: true, message: '请输入合同金额', trigger: 'blur' }],
  url: [{ required: true, message: '请上传合同附件', trigger: 'change' }],
  startTime: [
    {
      required: true,
      type: 'date',
      message: '请选择开始时间',
      trigger: 'change',
    },
  ],
  endTime: [
    {
      required: true,
      type: 'date',
      message: '请选择结束时间',
      trigger: 'change',
    },
  ],
  productId: [{ required: true, message: '请选择产品', trigger: 'change' }],
})
const down_index = ref()
const list = ref()
const total = ref()
const loading = ref(false)
const show_box = ref(false)
const height_size = ref(1)
const header_list = ref<any>([
  {
    label: '合同编号',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '合同名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '产品类型',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: store.state.product_list,
  },
  {
    label: '开始时间',
    value: '',
    showTable: true,
    type: 'date',
    isShow: false,
    options: [],
  },
  {
    label: '结束时间',
    value: '',
    showTable: true,
    type: 'date',
    isShow: false,
    options: [],
  },
  {
    label: '战略合作客户',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
  {
    label: '合同金额',
    value: ['', ''],
    showTable: true,
    type: 'input_number',
    isShow: false,
    options: [],
  },
  {
    label: '审核状态',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: [
      { value: '1', label: '待审核' },
      { value: '2', label: '已审核' },
    ],
  },
  {
    label: '合同状态',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: [
      { value: '0', label: '停用中' },
      { value: '1', label: '进行中' },
      { value: '2', label: '已暂停' },
      { value: '3', label: '已过期' },
    ],
  },
  {
    label: '备注',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
])
const page_data = ref({
  current: 1,
  pageSize: 1000,
  name: '',
  code: '',
  enterpriseName: '',
  startTime: '',
  endTime: '',
  remark: '',
  verifyStatus: '',
  status: '',
  amount: '',
  productId: '',
})
const add_form_data = ref({
  id: '',
  code: '',
  enterpriseId: '',
  name: '',
  startTime: '',
  endTime: '',
  amount: '',
  remark: '',
  status: 1,
  url: [],
  productId: '',
  fileNames: [],
})
const download = (e) => {
  axios
    .request({
      url: serviceApi.contract_download + '/' + e,
      method: 'get',
      responseType: 'blob',
    })
    .then((res1) => {
      console.log(res1)
      const blob = new Blob([res1 as any]) // res.data 为接口返回的数据，依实例而行
      const URL = window.URL.createObjectURL(blob) // 生成一个 Blob URL
      const fileName = add_form_data.value.fileNames[down_index.value] // 文件名+后缀
      const listNode = document.createElement('a')
      listNode.download = fileName as any
      listNode.style.display = 'none'
      listNode.href = URL // 文件流生成的url
      document.body.appendChild(listNode)
      listNode.click() // 模拟在按钮上实现一次鼠标点击
      window.URL.revokeObjectURL(listNode.href) // 释放 URL 对象
      document.body.removeChild(listNode) // 移除 a 标签
    })
}
const is_uploadImg = computed(() => {
  return add_form_data.value.url.length
})
const product_list = computed(() => {
  return store.state.product_list
})
onMounted(() => {
  max_height.value = window.innerHeight - 270 // 带分页的 table 高度
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item.path)
  })
  EventBus.on('refresh', () => {
    get_list()
    ElMessage.success('操作成功！')
  })
  EventBus.on('uploadSucc', () => {
    // 上传图片成功 取消验证提示
    console.log(is_uploadImg)
    if (is_uploadImg.value) {
      addcoopenterpriseform.value.clearValidate(['url'])
    }
  })
  get_list()
})
onUnmounted(() => {
  EventBus.off('refresh')
  EventBus.off('uploadSucc')
})
const contract_list = ref([])
const select_enterprise = (e) => {
  console.log(e)
  contract_list.value = []
  add_form_data.value.startTime = ''
  enterprise_list.value.some((item) => {
    if (item.id == e && item.levelId == '4') {
      axios
        .request({
          url: serviceApi.contract_list,
          method: 'post',
          data: { current: 1, pageSize: 1000, enterpriseId: e },
        })
        .then((res) => {
          console.log(res)
          contract_list.value = res.data.content
        })
        .catch((err) => {
          ElMessage.error(err)
        })
    }
    return item.id == e
  })
}
// 暂停日期 今天 <= time and 合同开始时间 <= time and  time < 结束时间 and  time <= 合同结束时间
const startTimeDisabled = (time) => {
  return suspend_form.value.endTime == ''
    ? time.getTime() < Date.now() - 8.64e7 ||
        time.getTime() < suspend_form.value.contract_startTime ||
        time.getTime() > suspend_form.value.contract_endTime
    : time.getTime() < Date.now() - 8.64e7 ||
        time.getTime() < suspend_form.value.contract_startTime ||
        time.getTime() > suspend_form.value.contract_endTime ||
        time.getTime() >= suspend_form.value.endTime
}
// 重启日期 今天 < time && time > 开始时间 and 合同开始时间 < time and  time <= 合同结束时间
const endTimeDisabled = (time) => {
  return suspend_form.value.startTime == ''
    ? time.getTime() <= Date.now() - 8.64e7 + 3600 * 1000 * 24 ||
        time.getTime() < suspend_form.value.contract_startTime ||
        time.getTime() > suspend_form.value.contract_endTime
    : time.getTime() <= Date.now() - 8.64e7 + 3600 * 1000 * 24 ||
        time.getTime() < suspend_form.value.contract_startTime ||
        time.getTime() > suspend_form.value.contract_endTime ||
        time.getTime() <= suspend_form.value.startTime
}
const suspend_form = ref({
  id: '',
  contractId: '',
  contract_startTime: '',
  contract_endTime: '',
  startTime: '',
  endTime: '',
  isPutOff: false,
})
const suspend_box = ref(false)
const suspend_list = (e) => {
  // 是否存在 待执行的暂停 （可编辑）
  let is_update = e.pauseTimeList.some((item) => {
    return item.status == 0
  })
  console.log(is_update)
  suspend_form.value = {
    id: is_update ? e.pauseTimeList[0].id : '', // id不为空则表示编辑
    contractId: e.id,
    contract_startTime: e.startTime,
    contract_endTime: e.endTime,
    startTime: is_update
      ? (parseInt(e?.pauseTimeList[0]?.startTime) as any)
      : '',
    endTime: is_update
      ? // date.parse 转换日期 东八区时间 （早上八点） 需指定时区  GMT +8
        e?.pauseTimeList[0]?.endTime == '待定日期'
        ? ''
        : (Date.parse(e.pauseTimeList[0]?.endTime + ' GMT +8') as any)
      : '',
    isPutOff: is_update ? e.pauseTimeList[0].isPutOff : false,
  }
  suspend_box.value = true
}
// 关闭暂停
const suspend_cancel = () => {
  ElMessageBox.confirm('确定关闭此次暂停操作', '提示', {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    closeOnClickModal: false,
    type: 'warning',
  })
    .then(() => {
      axios
        .request({
          url: serviceApi.contract_cancelPause + '/' + suspend_form.value.id,
          method: 'post',
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！')
          setTimeout(() => {
            get_list()
            suspend_box_cancel()
          }, 1000)
        })
    })
    .catch(() => {})
}
// 关闭暂停弹窗
const suspend_box_cancel = () => {
  suspend_form.value = {
    id: '',
    contractId: '',
    contract_startTime: '',
    contract_endTime: '',
    startTime: '',
    endTime: '',
    isPutOff: false,
  }
  suspend_box.value = false
}
const suspend_submit = () => {
  console.log(suspend_form.value)
  let startTime =
    suspend_form.value.startTime == '' || suspend_form.value.startTime === null
      ? '今日'
      : formatDate(suspend_form.value.startTime, 'YYYY-MM-DD')
  let endTime =
    suspend_form.value.endTime == '' || suspend_form.value.endTime === null
      ? '待定日期'
      : formatDate(suspend_form.value.endTime, 'YYYY-MM-DD')
  ElMessageBox.confirm(
    '确定于 ' + startTime + ' 至 ' + endTime + ' 暂停该战略合同？',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      closeOnClickModal: false,
      type: 'warning',
    }
  )
    .then(() => {
      axios
        .request({
          url:
            suspend_form.value.id == ''
              ? serviceApi.contract_savePauseTime
              : serviceApi.contract_updatePauseTime,
          method: 'post',
          data: suspend_form.value,
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！')
          setTimeout(() => {
            get_list()
            suspend_box_cancel()
          }, 1000)
        })
        .catch((err) => {
          ElMessage.error(err)
        })
    })
    .catch(() => {})
}
const restart_list = (e) => {
  ElMessageBox.confirm('确定重启该战略合同？', '提示', {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    closeOnClickModal: false,
    type: 'warning',
  })
    .then(() => {
      axios
        .request({
          url: serviceApi.contract_change + '/' + e.id + '/1',
          method: 'put',
        })
        .then(() => {
          ElMessage.success('操作成功！')
          setTimeout(() => {
            get_list()
          }, 1000)
        })
    })
    .catch(() => {})
}
const exam = () => {
  if (btn_loading.value) return
  btn_loading.value = true
  ElMessageBox.confirm('确定审核通过该战略合同？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: ' 取消',
    closeOnClickModal: false,
    type: 'warning',
  })
    .then(() => {
      axios
        .request({
          url: serviceApi.contract_pass + '/' + add_form_data.value.id,
          method: 'put',
        })
        .then(() => {
          ElMessage.success('操作成功！')
          btn_loading.value = false
          show_box.value = false
          is_exam.value = false
          setTimeout(() => {
            get_list()
          }, 1000)
        })
        .catch((err) => {
          ElMessage.error(err)
          btn_loading.value = false
        })
    })
    .catch(() => {
      btn_loading.value = false
    })
}
const is_exam = ref(false)
const pass_list = (e) => {
  is_exam.value = true
  edit_list(e)
}
const delete_id = ref()
const show_delete_box = ref(false)
const delete_box_status = ref()
const delete_name = ref()
const delete_list = (e) => {
  console.log(e)
  delete_box_status.value = e.type
  delete_id.value = e.item.id
  delete_name.value = e.item.name
  show_delete_box.value = true
}
const submit_delete = () => {
  // 删除
  axios
    .request({
      url: serviceApi.contract_crud + '/' + delete_id.value,
      method: 'delete',
    })
    .then(() => {
      ElMessage.success('操作成功！')
      show_delete_box.value = false
      setTimeout(() => {
        get_list()
      }, 1000)
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const verifyStatus = ref()
const edit_list = (e) => {
  console.log(e.url)
  add_form_data.value = {
    id: e.id,
    code: e.code,
    name: e.name,
    enterpriseId: e.enterpriseId,
    amount: e.amount,
    startTime: parseInt(e.startTime) as any,
    endTime: parseInt(e.endTime) as any,
    status: e.status,
    remark: e.remark,
    url: JSON.parse(e.url).map((item) => {
      return item.url
    }),
    productId: e.productId.dictCode,
    fileNames: JSON.parse(e.url).map((item) => {
      return item.name
    }),
  }
  verifyStatus.value = e.verifyStatus
  show_box.value = true
}
const btn_loading = ref(false)
const submit = async (formEl: FormInstance | undefined) => {
  console.log(add_form_data.value)
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return
      btn_loading.value = true
      let data = JSON.parse(JSON.stringify(add_form_data.value))
      data.attachmentList = []
      data.url.forEach((item, index) => {
        let item1 = {
          name: data.fileNames[index],
          url: item,
        }
        data.attachmentList.push(item1)
      })
      console.log(data)
      axios
        .request({
          url:
            data.id == ''
              ? serviceApi.contract_crud
              : serviceApi.contract_crud + '/' + data.id,
          method: data.id == '' ? 'post' : 'put',
          data: data,
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！')
          setTimeout(() => {
            btn_loading.value = false
            show_box.value = false
            get_list()
            resetForm(formEl)
          }, 1000)
        })
        .catch((err) => {
          btn_loading.value = false
          ElMessage.error(err)
        })
    }
  })
}
const enterprise_list = computed(() => {
  return store.state.enterprise_list
})
console.log(enterprise_list.value)
const get_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.contract_list,
      method: 'post',
      data: handle_search_key(page_data.value),
    })
    .then((res) => {
      if (res.data.content.length) {
        res.data.content.forEach((item) => {
          item.pauseTimeList.forEach((item1) => {
            item1.endTime =
              item1?.endTime === null
                ? '待定日期'
                : formatDate(parseInt(item1?.endTime), 'YYYY-MM-DD')
          })
          item.days =
            (item.endTime - Date.parse(new Date() as any)) /
            (24 * 60 * 60 * 1000)
          product_list.value.forEach((item1) => {
            if (item.productId == item1.dictCode) {
              item.productId = item1
            }
          })
        })
      }
      list.value = res.data.content
      total.value = parseInt(res.data.totalElements)
      loading.value = false
    })
    .catch((err) => {
      ElMessage.error(err)
      loading.value = false
    })
}
const search_key = () => {
  console.log(header_list.value)
  page_data.value = {
    current: 1,
    pageSize: 1000,
    enterpriseName: header_list.value[5].value,
    name: header_list.value[1].value,
    code: header_list.value[0].value,
    startTime: header_list.value[3].value,
    endTime: header_list.value[4].value,
    remark: header_list.value[9].value,
    verifyStatus: header_list.value[7].value,
    status: header_list.value[8].value,
    amount: header_list.value[6].value,
    productId: header_list.value[2].value,
  }
  get_list()
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    id: '',
    code: '',
    name: '',
    startTime: '',
    endTime: '',
    amount: '',
    remark: '',
    status: 1,
    enterpriseId: '',
    url: [],
    productId: '',
    fileNames: [],
  }
  contract_list.value = []
  suspend_form.value = {
    id: '',
    contractId: '',
    startTime: '',
    endTime: '',
    contract_startTime: '',
    contract_endTime: '',
    isPutOff: false,
  }
  suspend_box.value = false
  show_box.value = false
  is_exam.value = false
}
</script>

<style lang="scss" scoped></style>
